package com.suzhouhe.util.interceptor;

import com.suzhouhe.util.config.ResponseResult;
import com.suzhouhe.util.constans.ConfigConst;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 拦截处理结果
 *
 * @author suzhouhe
 * @date 2020-11-04 14:30
 **/
@Component
public class ResponseResultInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            if (ConfigConst.handlerMethodList.contains(handlerMethod)) {
                request.setAttribute(ConfigConst.RESPONSE_RESULT, true);
                return true;
            }
            if (handlerMethod.getBeanType().isAnnotationPresent(ResponseResult.class)
                    || handlerMethod.getMethod().isAnnotationPresent(ResponseResult.class)) {
                ConfigConst.handlerMethodList.add(handlerMethod);
                request.setAttribute(ConfigConst.RESPONSE_RESULT, true);
            }
        }
        return true;
    }
}
